<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/10/19
 * Time: 11:13
 */

namespace Biz\module\Classes;

use Biz\model\activity\GroupBuy;
use Biz\model\trade\OrderPay;
use Biz\module\Classes\OrderRefund as clsOrderRefund;
use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\model\trade\OrderRefund as mOrderRefund;
use Biz\model\trade\OrderOperateLog as mOrderOperateLog;
use Biz\module\Classes\mgt\OrderRefund as clsMgtOrderRefund;
use Biz\service\activity\GroupBuy as sGroupBuy;
use Biz\service\ShopInfo;
use Biz\service\trade\ShopAddress as sShopAddress;
use Doraemon\tools\Log;
use Doraemon\tools\MiniProgramConfig;
use Doraemon\tools\MiniProgramNotice;

class OrderGroupBuy
{
    const OP_TYPE_HAND = 1;//手工关闭团购订单
    const OP_TYPE_SYS = 2;//未成团自动关闭

    public static function cancelAndRefundOrder($orderNo, $adminUid = 0, $opType = self::OP_TYPE_HAND)
    {

        $orderInfo = mOrder::getOrderInfo($orderNo);


        if ($orderInfo['order_type'] != mOrder::ORDER_TYPE_GROUP_BUY) {
            throw new \Exception('请从正确渠道操作');
        }

        if($orderInfo['status'] == mOrder::STATUS_SEND_OUT){
            throw new \Exception('请从正确渠道操作');
        }

        if($orderInfo['refund_amount'] > 0 || $orderInfo['refunded_amount'] > 0){
            throw new \Exception('请确认该订单中的退款状态是否正确');
        }

        $orderSku = mOrderGoods::getFirstSkuInfo($orderNo);

        $data = [];
        $data['reason'] = 11;
        $data['refund_remark'] = '团购订单关闭';
        $data['images_content']='';

        if($orderInfo['status'] == mOrder::STATUS_WAIT_SEND) {
            $data['type_refund'] = mOrderRefund::TYPE_REFUND_AMOUNT;
            $data['receipt_status'] = mOrderRefund::RECEIPT_STATUS_NO;
        }

        $uid = $orderInfo['uid'];
        $skuId = $orderSku['sku_id'];
        $shopId = $orderInfo['shop_id'];

        //增加申请退款记录
        //增加同意退款记录
        $address = sShopAddress::getDefaultAddressByShopId($shopId);

        $addressId = !empty($address) ? $address['id'] : 0;

        $refundOrderNo = mOrderRefund::action(function () use ($uid, $shopId,$orderNo, $skuId, $data, $addressId) {

            $clsOrderRefund = new clsOrderRefund();

            $refundOrderNo = $clsOrderRefund->applyRefund($uid, $orderNo, $skuId, $data, false);

            if(!empty($refundOrderNo)){

                $clsMgtOrderRefund = new clsMgtOrderRefund();

                $clsMgtOrderRefund->agreeRefund($shopId, $refundOrderNo, $addressId, true, false);

            }


            return $refundOrderNo;
        });

        if (empty($refundOrderNo)) {
            throw new \Exception('关闭订单失败');
        }

        //增加订单退款记录
        $textContent = "【团购】手动关闭订购单并退款";
        if ($opType == self::OP_TYPE_SYS) {
            $textContent = "【团购】结束时未达到成团条件，自动批量关闭订单";
        }

        $result = mOrderOperateLog::createLog($shopId, $orderNo, mOrderOperateLog::TRADE_TYPE_ORDER_REFUND, [
            'operate_type'      => mOrderOperateLog::OPERATE_TYPE_CLOSE_GROUP_BUY,
            'operate_user_type' => mOrderOperateLog::OPERATE_USERTYPE_SYS,
            'operate_uid'       => $opType == self::OP_TYPE_SYS ? 0 : $adminUid,
        ], $refundOrderNo, $textContent, '', $data);

        if ($result->rowCount() == 0) {
            throw new \Exception('退款申请错误');
        }

        //团购订单，关闭时进行微信小程序的通知
        $noticeData = [
            'keyword1' => $orderInfo['pay_amount'],
            'keyword2' => $orderSku['title'],
            'keyword3' => $orderNo,
            'keyword7' => '抱歉，未达到组团条件，我们会在两个工作日内将款项返还到你的账户。'
        ];
        self::failGroupbuyReminderUser($orderNo,$noticeData);

    }

    public static function afterPaySuccessCallback($orderNo,$shopId,$skuTitle,$payAmount,$groupIds=[], $buyNum){

        if(empty($groupIds)){
            return;
        }

        try{
            sGroupBuy::increGroupCounter($groupIds,GroupBuy::COUNT_TYPE_BUYER ,$buyNum);

        }catch (\Exception $e){

        }
    }

    //成团提醒
    public static function succGroupbuyReminderUser($orderNo,$noticeData=[]){
        $parentNo = mOrder::getOrderParentNo($orderNo);

        $payInfos = OrderPay::getOrderPay("*",
            [
                'payWay' => OrderPay::PAY_WAY_TUAN_MINIPROGRAM,
                'orderNo' => $orderNo,
                'orderPno' => $parentNo,
                'status' => OrderPay::STATUS_PAIED
            ]);

        if (!empty($payInfos)) {
            foreach ($payInfos as $payInfo) {
                $payOrderInfo = json_decode($payInfo['pay_order_info'], true);
                parse_str($payOrderInfo['package'], $params);

                Log::debug('发送成团提醒操作',[$payOrderInfo['open_id'], MiniProgramNotice::MSG_TEMPLATE_ORDER_GROUPBUY_SUCC,
                    $params['prepay_id'], $orderNo, $noticeData]);

                MiniProgramNotice::sendNotice(MiniProgramConfig::APP_NAME_TUANGOU,$payOrderInfo['open_id'], MiniProgramNotice::MSG_TEMPLATE_ORDER_GROUPBUY_SUCC,
                    $params['prepay_id'], $orderNo, $noticeData);
            }
        }
    }
    //团购失败退款通知
    public static function failGroupbuyReminderUser($orderNo,$noticeData=[]){
        $parentNo = mOrder::getOrderParentNo($orderNo);

        $payInfos = OrderPay::getOrderPay("*",
            [
                'payWay' => OrderPay::PAY_WAY_TUAN_MINIPROGRAM,
                'orderNo' => $orderNo,
                'orderPno' => $parentNo,
                'status' => OrderPay::STATUS_PAIED
            ]);

        if (!empty($payInfos)) {
            foreach ($payInfos as $payInfo) {
                $payOrderInfo = json_decode($payInfo['pay_order_info'], true);
                parse_str($payOrderInfo['package'], $params);
                MiniProgramNotice::sendNotice(MiniProgramConfig::APP_NAME_TUANGOU,$payOrderInfo['open_id'], MiniProgramNotice::MSG_TEMPLATE_ORDER_GROUPBUY_FAIL,
                    $params['prepay_id'], $orderNo, $noticeData);
            }
        }
    }

}